package com.llk.rabbitmqlearn.rest;

import com.llk.rabbitmqlearn.config.RabbitConfig;
import com.llk.rabbitmqlearn.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@RestController
public class SendController {
    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 固定时间延迟队列
     *
     * @param message
     */
    @GetMapping("ttl/sendMsg/{message}")
    public void sendMsg(@PathVariable("message") String message) {
        log.info("当前时间：{},发送一条信息给两个 TTL 队列:{}", DateUtils.getDateStr(new Date(), DateUtils.FORMAT_PATTERN), message);
        rabbitTemplate.convertAndSend(RabbitConfig.NORMAL_EXCHANGE, RabbitConfig.NORMAL_ROUTING_KEY, "消息来自 ttl 为 10S 的队列: " + message);
        rabbitTemplate.convertAndSend(RabbitConfig.NORMAL_EXCHANGE, RabbitConfig.NORMAL_ROUTING_KEY_2, "消息来自 ttl 为 20S 的队列: " + message);
    }

    /**
     * 手动配置失效时间的延迟队列
     *
     * @param message
     * @param ttl
     */
    @GetMapping("ttl/sendMsg/{message}/{ttl}")
    public void sendMsg(@PathVariable("message") String message, @PathVariable("ttl") String ttl) {
        log.info("当前时间：{}, 发送一条信息给 TTL 队列:{}", DateUtils.getDateStr(new Date(), DateUtils.FORMAT_PATTERN), message);
        rabbitTemplate.convertAndSend(RabbitConfig.NORMAL_EXCHANGE, RabbitConfig.DELAY_ROUTING_KEY, message, correlationData -> {
            correlationData.getMessageProperties().setExpiration(ttl);
            return correlationData;
        });
    }

    /**
     * 高级发布确认
     *
     * @param message
     */
    @GetMapping("confirm/sendMessage/{message}")
    public void sendMessage(@PathVariable("message") String message) {
        log.info("发送消息内容为：{}", message);
        CorrelationData correlationData = new CorrelationData("1");
//        rabbitTemplate.convertAndSend(RabbitConfig.CONFIRM_EXCHANGE, RabbitConfig.CONFIRM_ROUTING_KEY, message, correlationData);
        // 模拟当交换机收不到消息场景
//        rabbitTemplate.convertAndSend(RabbitConfig.CONFIRM_EXCHANGE + "111", RabbitConfig.CONFIRM_ROUTING_KEY, message, correlationData);
        // 模拟队列收不到消息场景
        rabbitTemplate.convertAndSend(RabbitConfig.CONFIRM_EXCHANGE, RabbitConfig.CONFIRM_ROUTING_KEY+ "111", message, correlationData);
    }
}
